<script>
  import { onMount } from "svelte"

  let username = ''
  let password = ''
  let error = ''
  let logged = false;

  onMount(() => {
    fetch('/api/account/verify-login').then(res => res.json()).then(data => {
      if (data.status) {
        logged = true;
      } else {
        logged = false;
      }
    })
  })

  async function handleLogin() {
    const res = await fetch('/api/account/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), })
    const data = await res.json()
    if (data.status) {
      logged = true;
      username = '';
      password = '';
    } else {
      const data = await res.json()
      error = data.message || '登录失败'
    }
  }

  async function handleLogout() {
    await fetch('/api/account/logout', { method: 'GET' })
    logged = false;
    username = '';
    password = '';
  }
</script>

<div class="min-h-[calc(100vh-64px)] flex items-center justify-center bg-gray-50 px-4" >
  {#if logged}
    <div class="w-full max-w-md bg-white rounded-2xl shadow-lg p-8 flex flex-col items-center gap-4">
      <h2 class="text-xl font-bold text-gray-800 mb-2">您已登录</h2>
      <div class="flex gap-4 w-full justify-center">
        <a href="/" class="flex-1 inline-block bg-blue-50 text-blue-700 border border-blue-200 hover:bg-blue-100 font-medium py-2 rounded-lg transition text-center">返回首页</a>
        <button class="flex-1 bg-red-500 hover:bg-red-600 text-white font-medium py-2 rounded-lg transition" on:click={handleLogout}>退出登录</button>
      </div>
    </div>
  {:else}
  <div class="w-full max-w-md bg-white rounded-2xl shadow-lg p-8">
    <h1 class="text-2xl font-semibold text-center text-gray-800 mb-6"> 登录系统 </h1>
    {#if error} <p class="text-red-500 text-sm mb-4 text-center">{error}</p> {/if}
    <div class="space-y-4">
      <input class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:outline-none" placeholder="用户名" bind:value={username} />
      <input class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-blue-500 focus:outline-none" type="password" placeholder="密码" bind:value={password} />
      <button class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 rounded-xl transition" on:click={handleLogin} > 登录 </button>
    </div>
    <p class="text-sm text-gray-500 text-center mt-6"> 没有账号？ <a href="/account/register" class="text-blue-600 hover:underline" >立即注册</a ></p>
  </div>
  {/if}
</div>
